using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EnemyController : MonoBehaviour
{
    public float speed = 3f;
    public float changeDirectionTime = 2f;

    public bool isVertical;

    private float changeTimer;

    private Vector2 moveDirection;

    public AudioClip fixedClip;

    private bool isFixed;

    private Rigidbody2D rbody;

    private Animator anim;
    // Start is called before the first frame update
    void Start()
    {
        rbody = GetComponent<Rigidbody2D>();
        anim = GetComponent<Animator>();
        moveDirection = isVertical ? Vector2.up:Vector2.right ;
        changeTimer = changeDirectionTime;
        isFixed = false;
    }

    // Update is called once per frame
    void Update()
    {
        if (isFixed) return;
        changeTimer -= Time.deltaTime;
        if (changeTimer < 0)
        {
            moveDirection *=-1;
            changeTimer=changeDirectionTime;
        }
        Vector2 position=rbody.position;
        position.x += moveDirection.x*speed*Time.deltaTime;
        position.y += moveDirection.y * speed * Time.deltaTime;
        rbody.MovePosition(position);
        anim.SetFloat("movex",moveDirection.x);
        anim.SetFloat("movey", moveDirection.y);
    }

    void OnCollisionEnter2D(Collision2D other)
    {
        PlayerController pc = other.gameObject.GetComponent<PlayerController>();
        if (pc != null)
        {
            pc.ChangeHealth(-1);
        }
    }
    public void Fixed()
    {
        isFixed = true;
        AudoManager.instance.AudioPlay(fixedClip);
        rbody.simulated = false;
        anim.SetTrigger("fix");
        Destroy(gameObject);
    }
}
